package com.lanou3g.dmo;

import com.lanou3g.demo.dao.OrderDao;
import com.lanou3g.demo.db.DBConnector;
import com.lanou3g.demo.db.EntityHandler;
import com.lanou3g.demo.db.EntityListHandler;
import com.lanou3g.demo.db.KeyGenerateHandler;
import com.lanou3g.demo.entity.BookEntity;
import com.lanou3g.demo.entity.OrderEntity;
import com.lanou3g.demo.entity.OrderItemEntity;
import com.lanou3g.demo.entity.UserEntity;
import org.apache.commons.dbutils.QueryRunner;
import org.junit.Test;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class DBT {

    @Test
    public void a() throws SQLException {
        Connection conn = DBConnector.getInstance().getConnection();
        QueryRunner runner = new QueryRunner();
        String sql = "select * from orders where uid = ?";
        OrderEntity order = runner.query(conn, sql, new EntityHandler<>(OrderEntity.class), 1);
        System.out.println(order);

        String sql1 = "select * from orderitem where oid = ?";
        List<OrderItemEntity> query = runner.query(conn, sql, new EntityListHandler<>(OrderItemEntity.class), 1);

        System.out.println(query);
    }

    @Test
    public void selectUser() throws SQLException {
        Connection conn = DBConnector.getInstance().getConnection();
        QueryRunner runner = new QueryRunner();
        String sql="select * from tb_user where username=?";
        UserEntity userEntity = runner.query(conn, sql, new EntityHandler<>(UserEntity.class), "quting");
        System.out.println(userEntity);
    }

    @Test
    public void e() throws SQLException {
        Connection conn = DBConnector.getInstance().getConnection();
        QueryRunner runner = new QueryRunner();
        String sql = "select * from orders";
        List<OrderEntity> orderList = runner.query(conn, sql, new EntityListHandler<>(OrderEntity.class));
        for (OrderEntity order: orderList) {
            List<OrderItemEntity> orderItemList = OrderDao.selectOrderItem(order.getOid());
            order.setOrderItemList(orderItemList);
            for (OrderItemEntity orderItem : orderItemList) {
                BookEntity book = OrderDao.selectBook(orderItem.getBid());
                orderItem.setBookEntity(book);
            }
        }
        System.out.println(orderList);
    }

}
